package com.zja.servlet;


import com.zja.model.JsonResponse;
import com.zja.model.KnowledgeBase;
import com.zja.model.User;
import com.zja.service.Impl.KnowledgeBaseServiceImpl;
import com.zja.service.KnowledgeBaseService;
import com.zja.util.ServletUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Timestamp;

/**
 * @author JA
 * @date: 2025/5/3
 * description:创建知识库
 */
@WebServlet("/api/kb/create")
public class CreateKnowledgeBaseServlet extends HttpServlet {
    private final KnowledgeBaseService service = new KnowledgeBaseServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        req.setCharacterEncoding("UTF-8");


        String name = req.getParameter("name");
        String description = req.getParameter("description");
        String accessLevel = req.getParameter("accessLevel");

        // 获取当前登录用户
        HttpSession session = req.getSession(false);
        if (session == null || session.getAttribute("currentUser") == null) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("未登录！"));
            return;
        }


        User currentUser = (User) session.getAttribute("currentUser");

        KnowledgeBase kb = new KnowledgeBase();
        kb.setName(name);
        kb.setDescription(description);
        kb.setAccessLevel(accessLevel);
        kb.setCreatorId(currentUser.getId());
        //kb.setAdminId(currentUser.getId());
        Timestamp now = new Timestamp(System.currentTimeMillis());
        kb.setCreatedAt(now);
        kb.setUpdatedAt(now);

        boolean success = service.create(kb);
        if (success) {
            ServletUtil.writeJsonResponse(resp, JsonResponse.success("知识库创建成功！"));
        } else {
            ServletUtil.writeJsonResponse(resp, JsonResponse.error("创建失败"));
        }
    }
}
